Using the Laplace Transform to solvle a differential equation

Consider solving

$$ 3 \ddot{x} + 30 \dot{x} + 63 x = 4 \dot{g(t)} + 6 g(t) $$

where

$$ g(t) = 5 e^{-t} $$

and initial conditions are

$$ x(0) = 4, \dot{x}(0) = 7 $$

In [2]:
import numpy as np
import sympy
sympy.init_printing()

In [3]:
from sympy.abc import a, t, x, s, g, G, X
x, g, X = sympy.symbols('x, g, X', cls=sympy.Function)

In [4]:
x0 = 4
xd0 = 7

In [5]:
g = sympy.exp(-t)
g


Out[5]:
$$e^{- t}$$

Lets try the Laplace Transform on the input and check that it works


In [6]:
sympy.laplace_transform(g, t, s)[0]


Out[6]:
$$\frac{1}{s + 1}$$

Now lets define the EOMs

sympy doesn't handle undefined functions in the Laplace transform yet, so we will input the EOMS in the Laplace domain ourselves.

https://github.com/sympy/sympy/issues/7219#issuecomment-154768904


In [7]:
eoms = sympy.Eq(3*(s**2 * X(s) - s * x0 - xd0) +
               30 * (s * X(s) - x0) +
               63 * X(s), 
               sympy.laplace_transform(4 * sympy.diff(g, t) + 6 * g, t, s)[0])
eoms


Out[7]:
$$3 s^{2} X{\left (s \right )} + 30 s X{\left (s \right )} - 12 s + 63 X{\left (s \right )} - 141 = \frac{2}{s + 1}$$

Solve for $ X(s)$


In [8]:
XofS = sympy.solve(eoms, X(s))[0]
sympy.simplify(XofS)


Out[8]:
$$\frac{12 s^{2} + 153 s + 143}{3 \left(s^{3} + 11 s^{2} + 31 s + 21\right)}$$

Now just inverse Laplace to find the solution


In [9]:
sol = sympy.inverse_laplace_transform(XofS, s, t)
sol


Out[9]:
$$\frac{\theta\left(t\right)}{18} \left(e^{6 t} + 156 e^{4 t} - 85\right) e^{- 7 t}$$

Note

The $ \theta (t) $ is simply sympy's notation for a step function. This answer is only valid for $ t > 0$

We can generate a plot or evaluate


In [10]:
sympy.plot(sol, (t, 0.1, 2))


Out[10]:
<sympy.plotting.plot.Plot at 0x7f6189cbbc18>

In [11]:
sol.evalf(subs={t: 5})


Out[11]:
$$0.000376981542279453$$

A more complicated transformoration

$$ f(t) = 5 t^2 \cos (3 t + \frac{\pi}{4}) $$

In [21]:
t = sympy.symbols('t', positive=True)
s = sympy.symbols('s', complex=True)
f = 5 * t**2 * sympy.cos(3*t + sympy.pi/4)
f


Out[21]:
$$5 t^{2} \cos{\left (3 t + \frac{\pi}{4} \right )}$$

In [31]:
F = sympy.laplace_transform(5*t**2*sympy.cos(t), t, s, noconds=True)
F


Out[31]:
$$\frac{10 s \left(s^{2} - 3\right)}{\left(s^{2} + 1\right)^{3}}$$

Sympy has difficulty with this one. There are many related issues discussing these problems

https://github.com/sympy/sympy/issues/13491

Basically, Sympy is trying to do a numerical integral and having a hard time.